#!/bin/bash

# 获取所有 ROS 2 节点列表
nodes=$(ros2 node list 2>/dev/null)

# 检查是否有节点运行
if [ -z "$nodes" ]; then
  echo "No ROS 2 nodes are currently running."
  exit 0
fi

# 输出运行中的节点
echo "The following ROS 2 nodes are running:"
echo "$nodes"
echo

# 找到与 ROS 2 节点相关的进程并杀死它们
echo "Killing all ROS 2 nodes..."

# 获取运行中的 ROS 2 进程
processes=$(ps aux | grep ros2 | grep -v grep | awk '{print $2}')

if [ -z "$processes" ]; then
  echo "No ROS 2 processes found."
  exit 0
fi

# 遍历所有进程并终止
for pid in $processes; do
  echo "Killing process ID: $pid"
  kill -9 $pid || echo "Failed to kill process ID: $pid"
done

echo "All ROS 2 nodes have been killed."

